package com.ding.easycontroller.controller;

import com.ding.easycontroller.model.R;
import com.ding.easycontroller.pojo.WebSocketBrief;
import com.ding.easycontroller.pojo.WebSocketDetails;
import com.ding.easycontroller.pojo.WebSocketUpdateOrAddVO;
import com.ding.easycontroller.service.WebSocketService;
import com.ding.easycontroller.work.WebSocket;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/_config/websocket")
public class _WebSocket {


    @Autowired
    private WebSocketService websocketService;

    @PostMapping("/remove")
    public R remove(@RequestParam String id) throws IOException {
        websocketService.removeById(id);
        return R.OK;
    }

    @PostMapping("/updateOrAdd")
    public R updateOrAdd(@Validated WebSocketUpdateOrAddVO websocket) throws IOException {
        WebSocket c = new WebSocket();
        BeanUtils.copyProperties(websocket,c);
        websocketService.updateOrAdd(c);
        return R.ok(c.getId());
    }

    @GetMapping("/get")
    R get(@RequestParam String id) {
        WebSocket websocket = websocketService.getById(id);
        if (websocket==null){return R.NotFound;}
        WebSocketDetails details = new WebSocketDetails();
        BeanUtils.copyProperties(websocket, details);
        return R.ok(details);
    }


    @GetMapping("/all")
    R all() {
        List<WebSocket> websockets = websocketService.listAll();
        List<WebSocketBrief> websocketBriefs = new ArrayList<>();
        for (WebSocket websocket : websockets) {
            WebSocketBrief websocketBrief = new WebSocketBrief();
            BeanUtils.copyProperties(websocket, websocketBrief);
            websocketBriefs.add(websocketBrief);
        }
        return R.ok(websocketBriefs);
    }

}
